package org.mango.dict.service.impl;

import com.alibaba.fastjson.JSONArray;
import org.mango.dict.service.DictService;
import org.rex.DB;
import org.rex.RMap;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by meigang on 2018/1/31.
 */
@Service
@Transactional
public class DictServiceImpl implements DictService {

    @Override
    public JSONArray handleWords(String word) throws DBException {
        /**
         * 思路切换，不使用排列组合，因为24个字的排列组合算法太慢。得到的组合有24*23*...2*1。
         * 改用sql查询24个字得到24张成语中间表，再union all 中间表得到可能的成语组合，再group by order by count desc。
         * 查询语句
         SELECT ChengYu FROM `YesoulChenYu` WHERE ChengYu like '%千%'
         union all
         SELECT ChengYu FROM `YesoulChenYu` WHERE ChengYu like '%军%'
         union all
         SELECT ChengYu FROM `YesoulChenYu` WHERE ChengYu like '%万%'
         union all
         SELECT ChengYu FROM `YesoulChenYu` WHERE ChengYu like '%马%'
         */
        //1.先查询出可能的成语组合
        StringBuffer sql = new StringBuffer();
        for(int i=0;i<word.length();i++){
            Character schar = word.charAt(i);
            sql.append("select ChengYu from YesoulChenYu where ChengYu like '%"+schar+"%'");
            if(i!=word.length()-1){
                sql.append(" union all ");
            }
        }
        String doSql = "select t.ChengYu,count(1) count from("+sql.toString()+") t group by t.ChengYu order by count(1) desc";
        List<RMap> rmList = DB.getMapList(doSql);
        //2.过滤成语里的字，需要都在24个字内，排除掉不在的
        List<Map<String,Object>> rsmap = new ArrayList<>();
        for(RMap rm : rmList){
            String cy = rm.getString("chengyu");
            if(this.cyInWord(cy,word)){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("cy",cy);
                rsmap.add(map);
            }
        }
        return (JSONArray) JSONArray.toJSON(rsmap);
    }

    private boolean cyInWord(String cy, String word) {
        boolean b = true;
        for(int i=0;i<cy.length();i++) {
            Character schar = cy.charAt(i);
            if(word.contains(schar.toString())){

            }else{
                b = false;
                break;
            }
        }
        return b;
    }
}
